package main

import (
	"github.com/gin-gonic/gin"
	"fmt"
	"log"
	"net/http"
	"FileUploadAndDownload/utils"
	"time"
)

func main() {

	utils.PrintIP()
	time.Sleep(5 * time.Second)

	// 创建一个默认的路由引擎
	r := gin.Default()

	r.Static("/static", "./static")

	r.LoadHTMLGlob("templates/**/*")

	r.GET("/api", func(c *gin.Context) {

		clientip := c.ClientIP()
		hostname := c.Request.Host

		// 获取 Hostname 地址. Client IP
		fmt.Printf("clientip : %s\n", clientip)
		fmt.Printf("Hostname : %s\n", hostname)

		c.HTML(200,"get/API.html", gin.H{
			"uploadfile": fmt.Sprintf("http://%s/static/upload.html", hostname),
			"getclientip": fmt.Sprintf("http://%s/getip", hostname),
			"hostname": hostname,
			"getserverip": fmt.Sprintf("http://%s/serverip", hostname),
		})
	})

	r.GET("serverip", func(c *gin.Context) {
		// 获取Server IP 地址
		_ , err := utils.GetServerIP()
		if err != nil {
			fmt.Println("Error getting server IP:", err)
			return
		}

		serverip := utils.GetAllServerIP()


		fmt.Println(serverip)

		c.JSON(http.StatusOK, gin.H{
			"serverip": serverip,
			//Dictserverip,
		})
	})

	r.GET("getip", func(c *gin.Context) {
		clientIP := c.ClientIP()
		c.HTML(http.StatusOK, "get/GetIP.html", gin.H{
			"clientip": clientIP,
		})
	})

	r.MaxMultipartMemory = 7 << 30 // 8 G

	r.POST("/upload", func(c *gin.Context) {
		// 单个文件
		file, err := c.FormFile("f1")
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{
				"message": err.Error(),
			})
			return
		}

		log.Println(file.Filename)
		dst := fmt.Sprintf("./%s", file.Filename)
		// 上传文件到指定的目录
		c.SaveUploadedFile(file, dst)
		c.JSON(http.StatusOK, gin.H{
			"message": fmt.Sprintf("'%s' uploaded!", file.Filename),
			"status":  200,
		})
	})
	// 启动HTTP服务，默认在0.0.0.0:8080启动服务
	r.Run(":10086")
}
